package com.work.demo.entity;

import lombok.Data;

import java.util.Collections;
import java.util.List;

/**
 * 带分页的结果集
 *
 * @author sanbanfu
 * @date 2019-08-20
 */
@Data
public class PagedData<T> {

    public static final int DEFAULT_PAGE_SIZE = 20;

    /**
     * 数据总数
     */
    private long total;

    /**
     * 当前页数
     */
    private int page;

    /**
     * 页容量
     */
    private int size;

    /**
     * 列表元素
     */
    private List<T> data;

    /**
     * 总页数
     */
    private long pages;


    public static <T> PagedData<T> build(List<T> list, long total, int page) {
        return build(list, total, page, DEFAULT_PAGE_SIZE);
    }

    public static <T> PagedData<T> build(List<T> list, long total, int page, int size) {
        if (size <= 0) {
            throw new IllegalArgumentException("size mast > 0");
        }
        long pages = page == 0 ? 1 : total % size == 0 ? (total / size) : (total / size) + 1;
        return build(list, total, page, size, pages);
    }

    public static <T> PagedData<T> build(List<T> list, long total, int page, int size, long pages) {
        if (size <= 0) {
            throw new IllegalArgumentException("size mast > 0");
        }
        PagedData<T> paginationVO = new PagedData<>();
        paginationVO.setData(list != null ? list : Collections.emptyList());
        paginationVO.setTotal(total);
        paginationVO.setPage(page);
        paginationVO.setPages(pages);
        paginationVO.setSize(size);
        return paginationVO;
    }

    public static <T> PagedData<T> empty(int page, int size, long total) {
        PagedData<T> paginationVO = new PagedData<>();
        paginationVO.setData(Collections.emptyList());
        paginationVO.setTotal(total);
        paginationVO.setPage(page);
        paginationVO.setSize(size);
        return paginationVO;
    }

    public static <T> PagedData<T> empty(int page, int size) {
        return empty(page, size, 0);
    }

    public static <T> PagedData<T> empty(int page) {
        return empty(page, 0, 0);
    }
}
